<template>
  <div>
    <div class="margin-container-list">
      <el-tabs v-model="selectStatus" @tab-click="selectStatusClick">
        <el-tab-pane label="已选商品" name="1"></el-tab-pane>
        <el-tab-pane label="未选商品" name="0" v-if="groupObj.goodsGroupType !== 2"></el-tab-pane>
      </el-tabs>
      <!--顶部搜索 -->
      <div class="top-operate">
        <div>
          <div class="float-l">
            <el-select class="select-class" v-model="textCol" style="width: 120px">
              <el-option label="商品名称" value="title"></el-option>
              <el-option label="商品货号" value="goodsCode"></el-option>
            </el-select>
            <el-input @keyup.enter.native="handleSearch" v-model="searchKeyword" placeholder="请输入关键词" style="width: 200px"></el-input>
            <el-cascader v-model="categoryIds" placeholder="选择商品零售分类" :props="{ checkStrictly: true }" change-on-select :options="categoryData" class="default-input" filterable clearable style="width: 250px"></el-cascader>
            <el-select v-model="searchListQuery.goodsStatus" v-if="selectStatus == 1 && groupType !== 2" placeholder="选择上下架状态" clearable style="width: 150px">
              <el-option label="上架" value="1"></el-option>
              <el-option label="下架" value="0"></el-option>
            </el-select>
            <el-select v-model="searchListQuery.goodsType" v-if="groupType !== 2" placeholder="选择商品类型" clearable style="width: 150px">
              <el-option label="零售商品" value="30"></el-option>
              <el-option label="批发商品" value="31"></el-option>
              <el-option label="零售+批发商品" value="32"></el-option>
            </el-select>
            <el-select v-model="searchListQuery.goodsSource" v-if="groupType == 2" placeholder="选择商品来源" clearable style="width: 150px">
              <el-option label="企业" value="0"></el-option>
              <el-option label="供应商" value="1"></el-option>
              <el-option label="淘宝商品" value="2"></el-option>
              <el-option label="供货联盟" value="3"></el-option>
            </el-select>
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button plain @click="resetSearch">重置</el-button>
          </div>
          <div class="btn-search" v-if="groupObj.goodsGroupType !== 2">
            <el-button v-if="selectStatus == 0" @click="handleBatchSelect" type="primary">批量添加</el-button>
            <el-button v-if="selectStatus == 1" @click="handleBatchRemove" type="primary">批量移除</el-button>
            <!-- 产品说暂时先隐藏 -->
            <!-- <el-upload v-if="selectStatus == 1" name="files"
              action="/api/common/uploadFiles"
              :multiple="false"
              :show-file-list="false"
              :data="token"
              :before-upload="beforeUploadFile"
              :on-success="handleUploadSuccess">
              <el-button size="small" :loading="fileLoading" type="primary">批量导入</el-button>
            </el-upload>
            <span v-if="selectStatus == 1" class="font-blue"><el-button @click="downloadTemplate" type="text">下载导入模板</el-button></span> -->
          </div>
        </div>
      </div>
      
      <!-- 内容列表 -->
      <div class="table-container">
        <div class="scroll-layer-box">
          <el-table ref="multipleTable" :data="goodsList" v-loading="listLoading" @selection-change="handleSelectionChange" element-loading-text="加载中" style="width: 100%" >
          <el-table-column width="50px" type="selection"></el-table-column>
          <el-table-column min-width="320px" label="商品名称" prop="title">
            <template slot-scope="scope">
              <div class="flex v-align-c cursor-p">
                <label><img :src="scope.row.mainImage" class="user-avatar"></label>
                <div class="font-14 pad-l-10">
                  <div>{{scope.row.title}}</div>
                  <div v-if="groupType !== 2">
                    <span class="font-gray">商品货号：{{scope.row.goodsCode}}</span>
                  </div>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column width="100px" label="上下架状态" prop="goodsStatus" align="center">
            <template slot-scope="scope">
              <span v-if="scope.row.goodsType === 30">
                <span>{{dict.goodsStatus[scope.row.goodsStatus]}}</span>
              </span>
              <span v-else-if="scope.row.goodsType === 31">
                <span>{{dict.goodsStatus[scope.row.wholesaleGoodsStatus]}}</span>
              </span>
              <span v-else-if="scope.row.goodsType === 32">
                <span v-if="groupType == 2">{{dict.goodsStatus[scope.row.wholesaleGoodsStatus]}}</span>
                <span v-else>{{dict.goodsStatus[scope.row.wholesaleGoodsStatus || scope.row.goodsStatus]}}</span>
              </span>
            </template>
          </el-table-column>
          <el-table-column width="120px" label="零售价格(元)" prop="sellPrice" align="center" v-if="groupType !== 2"></el-table-column>
          <el-table-column width="100px" label="库存" prop="stock" align="center">
            <template slot-scope="scope">
              {{scope.row.stock || 0 }}
            </template>
          </el-table-column>
          <el-table-column width="120px" label="商品类型" prop="goodsType" v-if="groupType !== 2" align="center">
            <template slot-scope="scope">
              {{dict.goodsType[scope.row.goodsType]}}
            </template>
          </el-table-column>
          <el-table-column width="120px" label="商品来源" prop="goodsSource" v-if="groupType == 2" align="center">
            <template slot-scope="scope">
              <div v-if="scope.row.goodsSource == 0">企业</div>
              <div v-if="scope.row.goodsSource == 1">供应商</div>
              <div v-if="scope.row.goodsSource == 2">淘宝商品</div>
              <div v-if="scope.row.goodsSource == 3">供货联盟</div>
            </template>
          </el-table-column>
          <el-table-column width="120px" label="起批数" prop="wholesaleNum" v-if="groupType == 2" align="center"> 
            <template slot-scope="scope">
              {{ scope.row.wholesaleNum }}
            </template>
          </el-table-column>
          <el-table-column width="150px" label="操作" v-if="groupObj.goodsGroupType !== 2">
            <template slot-scope="scope">
              <el-button v-if="selectStatus == 1" type="primary" @click="removeGoodsId(scope.row.goodsId)">移除</el-button>
              <el-button v-if="selectStatus == 0" type="primary" @click="addGoodsId(scope.row.goodsId)">添加</el-button>
            </template>
          </el-table-column>
        </el-table>
        </div>
      </div>
        <!-- 列表分页 -->
        <div class="pagination">
          <el-pagination background 
            @size-change="handleSizeChange" 
            @current-change="handleCurrentChange"
            :current-page="searchListQuery.currentPage"
            :page-sizes="[10, 20, 50, 100]" 
            :page-size="searchListQuery.size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
          </el-pagination>
        </div>
      
        <div class="dialog-footer mar-b-20">
          <el-button type="primary" v-if="groupObj.goodsGroupType !== 2" @click="saveGoodsIds">保存</el-button>
          <el-button plain @click="doCancel">取消</el-button>
        </div>
    </div>
  </div>
</template>

<script>
  import { pageGroupSelectGoods, listGoodsCategory } from '@/api/goods/goods'
  import { downloadFile, getDictByGroupName } from '@/api/common/common'
  import { saveGoodsGroupDetail } from '@/api/goods/goodsGroup'
  import { getToken } from '@/utils/auth'

  export default {
    components: {},
    props: {
      showFlag: {
        type: Boolean,
        default() {
          return false
        }
      },
      // 商品组对象
      groupObj: {
        type: Object
      },
      groupType: {
        type: Number
      }
    },
    data() {
      return {
        token: '',
        total: 0,
        listLoading: true,
        searchListQuery: {
          enterpriseId: this.getEnterpriseId(),
          currentPage: 1,
          size: 10,
          title: '',
          goodsStatus: '',
          goodsType: '',
          goodsSource: '',
          goodsIds: []
        },
        textCol: 'title',
        searchKeyword: '',
        categoryIds: [],
        dict: {
          goodsStatus: {},
          goodsType: {}
        },
        categoryData: [],
        goodsList: [],
        // 初始选中商品id
        initGoodsIds: [],
        // 选中商品id
        selectedGoodsIds: [],
        // 选中tab
        selectStatus: '1',
        // 勾选商品
        pageSelection: [],
        loading: false,
        fileLoading: false
      }
    },
    watch: {
      showFlag(val) {
        if (val) {
          this.selectStatus = '1'
          this.groupObj.detailList.forEach(o => {
            this.initGoodsIds.push(o.goodsId)
            this.selectedGoodsIds.push(o.goodsId)
          })
          this.resetSearch()
        } else {
          this.initGoodsIds = []
          this.selectedGoodsIds = []
        }
      }
    },
    // 初始化页面
    created() {
      this.token = { accessToken: getToken() }
      this.groupObj.detailList.forEach(o => {
        this.initGoodsIds.push(o.goodsId)
        this.selectedGoodsIds.push(o.goodsId)
      })
      this.initDict()
      this.listGoodsCategory()
      this.initGoodsList()
    },
    methods: {
      // tab切换事件
      selectStatusClick() {
        this.resetSearch()
      },
      // 初始化数据字典
      initDict() {
        getDictByGroupName('ProjectGoodsDTO').then(response => {
          this.dict = response.data
        })
      },
      // 获取类目
      listGoodsCategory() {
        listGoodsCategory(this.getEnterpriseId()).then(response => {
          this.categoryData = response.data
        })
      },
      // 获取商品列表
      initGoodsList() {
        this.listLoading = true
        this.searchListQuery.title = ''
        this.searchListQuery.goodsCode = ''
        this.searchListQuery[this.textCol] = this.searchKeyword
        this.searchListQuery.selectStatus = this.selectStatus
        this.searchListQuery.goodsIds = this.selectedGoodsIds.join(',')
        this.searchListQuery.oneCategoryId = this.categoryIds.length > 0 ? this.categoryIds[0] : ''
        this.searchListQuery.twoCategoryId = this.categoryIds.length > 1 ? this.categoryIds[1] : ''
        this.searchListQuery.threeCategoryId = this.categoryIds.length > 2 ? this.categoryIds[2] : ''
        this.searchListQuery.groupType = this.groupType
        if (this.groupType === 2) {
          this.searchListQuery.goodsTypes = '31,32'
        }
        pageGroupSelectGoods(this.searchListQuery).then(response => {
          this.total = response.data.total
          this.goodsList = response.data.records
          this.listLoading = false
        })
      },
      // 查询事件
      handleSearch() {
        this.searchListQuery.currentPage = 1
        if (this.groupType === 2) {
          this.searchListQuery.goodsTypes = '31,32'
        }
        this.initGoodsList()
      },
      // 重置事件
      resetSearch() {
        this.searchListQuery = {
          enterpriseId: this.getEnterpriseId(),
          currentPage: 1,
          size: 10,
          title: '',
          goodsStatus: '',
          goodsType: ''
        }
        this.textCol = 'title'
        this.searchKeyword = ''
        this.categoryIds = []
        this.initGoodsList()
      },
      // 移除商品
      removeGoodsId(goodsId) {
        this.selectedGoodsIds.splice(this.selectedGoodsIds.findIndex(e => e === goodsId), 1)
        this.initGoodsList()
      },
      // 添加商品
      addGoodsId(goodsId) {
        this.selectedGoodsIds.push(goodsId)
        this.initGoodsList()
      },
      // 批量移除商品
      handleBatchRemove() {
        if (this.pageSelection.length === 0) {
          this.$message({ message: '请勾选商品', type: 'warning' })
          return
        }
        const goodsIds = this.pageSelection[this.searchListQuery.currentPage]
        goodsIds.forEach(goodsId => this.selectedGoodsIds.splice(this.selectedGoodsIds.findIndex(e => e === goodsId), 1))
        this.initGoodsList()
      },
      // 批量选择商品
      handleBatchSelect() {
        if (this.pageSelection.length === 0) {
          this.$message({ message: '请勾选商品', type: 'warning' })
          return
        }
        const goodsIds = this.pageSelection[this.searchListQuery.currentPage]
        goodsIds.forEach(goodsId => this.selectedGoodsIds.push(goodsId))
        this.initGoodsList()
      },
      // 更改当前页数
      handleCurrentChange(val) {
        this.searchListQuery.currentPage = val
        this.initGoodsList()
      },
      // 更改当前页面大小
      handleSizeChange(val) {
        this.searchListQuery.size = val
        this.initGoodsList()
      },
      // 勾选
      handleSelectionChange(items) {
        if (items.length === 0) {
          this.pageSelection[this.searchListQuery.currentPage] = []
        } else {
          this.pageSelection[this.searchListQuery.currentPage] = items.map(item => item.goodsId)
        }
      },
      // 保存事件
      saveGoodsIds() {
        this.listLoading = true
        if (this.compareOldAndNow()) {
          this.$emit('saveDetail', false)
        } else {
          const form = {
            goodsGroupId: this.groupObj.goodsGroupId,
            goodsIds: this.selectedGoodsIds
          }
          saveGoodsGroupDetail(form).then(response => {
            if (response.isError) return
            this.$emit('saveDetail', true)
            this.$message({ type: 'success', message: '保存成功!' })
          })
        }
      },
      // 取消事件
      doCancel() {
        this.$emit('saveDetail', false)
      },
      // 比较新旧值
      compareOldAndNow() {
        const old = this.initGoodsIds.join(',')
        const now = this.selectedGoodsIds.join(',')
        return old === now
      },
      // 下载模板事件
      downloadTemplate() {
        downloadFile('https://veekrayimg.joinsun.vip/upload/edb56cb6f49918d5bd1790dca2a9bfe3.xlsx', {}, '导入商品模板')
      },
      // 文件上传前校验
      beforeUploadFile(file) {
        const ext = file.name.substring(file.name.lastIndexOf('.') + 1)
        if (ext !== 'xlsx') {
          this.$message.error('请上传xlsx格式的Excel')
          return false
        }
        this.fileLoading = true
        return true
      },
      // 文件上传成功后事件
      handleUploadSuccess(res, file) {
        this.fileLoading = false
        if (res.code !== 101) {
          this.$message.error(res.msg)
          return
        }
        const params = {
          enterpriseId: this.getEnterpriseId(),
          goodsGroupId: this.groupObj.goodsGroupId,
          fileUrl: res.data[0],
          goodsIds: this.selectedGoodsIds
        }
        this.$bus.$emit('asyncHandle', '200003', params, () => {
          this.$emit('saveDetail', true)
        })
      }
    }
  }
</script>

<style lang="less" scoped>
  .user-avatar {
    width: 68px;
    height: 68px;
    display: block;
    padding: 1px;
    border: #efefef 1px solid;
  }
  .fotter-box {
    position: absolute;
    background: #fff;
    bottom: 12px;
    left: 50%;
    transform: translateX(-50%);
  }
</style>